#include <stdio.h>
#include "exception.h"
#include "utils.h"
#include "commands.h"
#include "lexic.h"

/* Prototypes */
static void initDatabase(void);
static void printHeader(void);
static void loadBasicProgram(void);
static void printLine(lineT line);

int main() {
	int value, currentRow;
	string input, token;
	expressionADT exp;
	lineT line, debug;

	// Init the database:
	initDatabase();

	// Prints the header:
	printHeader();
	
	// Load an example:
	loadBasicProgram();
	debug.cmd = "LIST";
	executeCommand(debug);

	// Main loop:
	while (TRUE) {
		try {
			// 1. Get input:
			input = getInput();

			// 2. Handle the input string:
			line = handleInput(input);

			// 3.1. Run the line:
			if (runnableLine(line)) {
				//printf("\n-> Execute command:\n");
				executeCommand(line);
			}
			// 3.2. Save & handle input:
			else if (line.row != -1) {
				if (StringEqual(line.cmd, ""))
					deleteLine(line);
				else
					saveLine(line);
			} else {
				printf("The command isn't valid.\n");
			}
			
			except(ErrorException)
				printf("Error: %s\n", (string)GetExceptionValue());
		} endtry;
	}
	system("pause");
}

/* Prints the header */
static void printHeader() {
	printf(" --- Mini-Basic ---\n");
	printf("Code-monkeys: Robert Olsson & Fredrik Dahlberg\n");
	printf("Print HELP to find a list of available commands.\n\n");
}

/* Initalizes the database */
static void initDatabase() {
	int i;

	// Database struct:
	db = New(dbT);

	// Initalize the command table:
	initCommandTable();

	// Variable table:
	InitVariableTable();
	//db->varTable = variableTable;
	
	// Scanner:
	db->scanner = NewScanner();
	SetScannerSpaceOption(db->scanner, IgnoreSpaces);

	// Parsed lines:
	db->lines.size = NUM_ROWS;
	db->lines.numRows = 0;
	db->lines.entries = NewArray(sizeof(lineT) * db->lines.size, lineT);
	for (i=0; i<db->lines.size; i++) {
		db->lines.entries[i].row = -1;
		db->lines.entries[i].cmd = NULL;
		db->lines.entries[i].rest = NULL;
	}

	// Program Counter (PC):
	db->PC = 0;
}

/* Loads a BASIC program */
static void loadBasicProgram() {
	string filename, input;
	FILE *fp;
	lineT line;

	printf("\n-- Loading Basic program ---\n\n");
	printf("Enter filename [basic-X.prg, X=1-3]:\n");
	printf("=> ");
	filename = GetLine();

	if ((fp = fopen(filename, "r")) != NULL) {
		while ((input = ReadLine(fp)) != NULL) {
			line = handleInput(ConvertToUpperCase(input));
			saveLine(line);
		}
		fclose(fp);
	}
}

/* DEBUG: prints stored data for a given line index */
static void printLine(lineT line) {
	printf("%s\n", line.rest);
	printf("  row:\t\t%d\n", line.row);
	printf("  cmd:\t\t%s\n", line.cmd);
}